<template>
  <el-form ref="roleForm" :model="roleForm" :rules="roleRules" label-width="100px">
    <el-form-item label="角色名称" prop="name">
      <el-input v-model="roleForm.name" />
    </el-form-item>
    <el-form-item label="角色描述">
      <el-input v-model="roleForm.description" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">添加</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { addRole, editRole } from '@/api/setting.js'

export default {
  name: 'Setdialog',
  props: {
    row: {
      type: [Object, Array],
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      roleForm: {
        name: '',
        description: ''
      },
      roleRules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    // 侦听isEdit的值的变化当isEdit为true时给替换掉当前的表单里的值
    isEdit: {
      handler(newVal, oldVal) {
        // console.log(newVal)
        if (newVal) {
          this.roleForm = JSON.parse(JSON.stringify(this.row))
        }
      },
      immediate: true
    }
  },

  methods: {
    // 点击
    submit() {
      this.$refs.roleForm.validate(result => {
        if (result) {
        //   console.log(this.isEdit)
          return this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    // 添加
    async doAdd() {
      const res = await addRole(this.roleForm)
      if (res.code === 10000) {
        this.clearForm()
        this.$message.success('添加角色成功!')
        this.$emit('success')
      }
    },
    // 修改
    async doEdit() {
      // console.log(this.roleForm.id)
      const res = await editRole(this.roleForm)
      //   console.log(res)
      if (res.code === 10000) {
        this.clearForm()
        this.$message.success('修改成功!')
        this.$emit('success')
      }
    },
    // 取消按钮
    cancel() {
      this.clearForm()

      this.$emit('success')
    },
    // 清空表单
    clearForm() {
      this.roleForm = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
